package com.dabai.sas.activitys;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.dabai.sas.R;
import com.dabai.sas.utils.DabaiUtils;
import com.dabai.sas.utils.FileUtil;
import com.dabai.sas.utils.KFileUtil;
import com.dabai.sas.utils.UriUtils;
import com.google.android.material.chip.Chip;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.yuyh.jsonviewer.library.JsonRecyclerView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class JsonViewerActivity extends AppCompatActivity {

    TextView tv1;
    Chip chip1;
    Context context;
    private JsonRecyclerView mRecyclewView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_viewer);

        context = getApplicationContext();

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);


        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DabaiUtils.showToast(context, "请点击申请'储存权限'!");
            startActivity(new Intent(this, PermissionsActivity.class));
            finish();
            return;
        }

        tv1 = findViewById(R.id.textView1);
        chip1 = findViewById(R.id.chip1);
        mRecyclewView = findViewById(R.id.rv_json);

        //设置 jsonviewer的 code 颜色
        // Color
        mRecyclewView.setKeyColor(Color.parseColor("#9C27B0"));
        mRecyclewView.setValueTextColor(Color.parseColor("#4CAF50"));
        mRecyclewView.setBracesColor(Color.parseColor("#01579B"));
        // TextSize
        mRecyclewView.setTextSize(18);

        init();

    }

    /**
     * 程序启动
     */
    private void init() {

        try {


            //拿到uri
            Uri uri = getIntent().getData();
            String fileText = "";

            if (uri.toString().startsWith("file:///")) {
                File file = new File(FileUtil.getFileAbsolutePath(this, uri));

                tv1.setText(file.getName());
                fileText = new KFileUtil().readText(file);

            }else {
                UriUtils file = new UriUtils(context, uri);
                tv1.setText(file.getFileName());
                fileText = file.readFileText();

            }

            chip1.setText("字数:" + fileText.length());

            //检查 json 内容 能否解析
            if (isJson(fileText)) {
                mRecyclewView.bindJson(fileText);
            } else {
                Toast.makeText(context, "Json内容异常,请使用文本查看器打开。", Toast.LENGTH_SHORT).show();
                finish();
            }

        } catch (Exception e) {
            Toast.makeText(context, "程序异常!", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

    }

    public static boolean isJson(String content) {
        if (content.isEmpty()) {
            return false;
        }
        boolean isJsonObject = true;
        boolean isJsonArray = true;
        try {
            JSONObject.parseObject(content);
        } catch (Exception e) {
            isJsonObject = false;
        }
        try {
            JSONObject.parseArray(content);
        } catch (Exception e) {
            isJsonArray = false;
        }
        if (!isJsonObject && !isJsonArray) { //不是json格式
            return false;
        }
        return true;
    }

    //通过URI读取文本的方法
    private String readDocument(Uri uri) {
        StringBuffer sb1 = new StringBuffer();
        if (uri != null) {
            InputStream inputStream = null;
            try {
                // 获取 OutputStream
                inputStream = context.getContentResolver().openInputStream(uri);

                int byteCount = 0;
                byte[] bytes = new byte[1024];

                while ((byteCount = inputStream.read(bytes)) != -1) {
                    sb1.append(new String(bytes, 0, byteCount));
                }

            } catch (IOException e) {

            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.fillInStackTrace();
                    }
                }
            }
        }
        return sb1.toString();
    }

    public void showDialog(Object text) {
        new AlertDialog.Builder(this).setTitle("提示").setMessage(text + "").show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}